﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WenSkin.Forms
{
    public partial class FormSqlServerConfig : Form
    {
        public FormSqlServerConfig()
        {
            InitializeComponent();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            OpenConnect();
        }
        private void OpenConnect()
        {
            SqlServerConnect connect = new SqlServerConnect();
            textBox_ServerAddress.Text = connect.Server;
            textBox_SqlserverDataBase.Text = connect.DataBase;
            textBox_UserID.Text = connect.UserID;
            textBox_Password.Text = connect.Password;
        }

        private void wenButton1_Click(object sender, EventArgs e)
        {
            if (LogonTest())
            {
                MessageBox.Show("数据连接成功！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private bool LogonTest()
        {
            var sqlCon = new SqlServerConnect(textBox_ServerAddress.Text, textBox_SqlserverDataBase.Text, textBox_UserID.Text, textBox_Password.Text);
            string Contr = sqlCon.ConStr;
            try
            {
                SqlConnection conn = new SqlConnection(Contr);
                conn.Open();
                if (conn.State == ConnectionState.Open)
                {
                    return true;
                }
            }
            catch
            {
                MessageBox.Show("数据连接失败！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return false;
        }

        private void wenButton2_Click(object sender, EventArgs e)
        {
            if (LogonTest())
            {
                var sqlcon = new SqlServerConnect(
                    textBox_ServerAddress.Text,
                    textBox_SqlserverDataBase.Text,
                    textBox_UserID.Text,
                    textBox_Password.Text);
                sqlcon.SaveConnectToFile();
                MessageBox.Show("保存成功！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DialogResult = DialogResult.OK;
            }
        }
    }
}